<script setup>
import { useRouter } from 'vue-router'
import { useForgotState } from '@/stores/index.js'
import { ArrowCircleRight } from '@icon-park/vue-next'
import { ref } from 'vue'
import { checkECodeService, getECodeService } from '@/api/common.js'
import { successMsg } from '@/utils/sendMsgUtils.js'


const router = useRouter()
const forgotState = useForgotState()

// 定义按钮状态和文本
const isDisabled = ref(false)
const buttonText = ref('获取验证码')

const getECode = async () => {

  const resp = await getECodeService(forgotState.getFUser())
  if (resp.code === 1) {
    successMsg('验证码发送成功， 请留意邮箱')
    // 禁用按钮并开始倒计时
    isDisabled.value = true
    let countdown = 60 // 60 秒倒计时
    buttonText.value = `${countdown}秒后可再次点击`

    const timer = setInterval(() => {
      countdown--
      buttonText.value = `${countdown}秒后可再次点击`

      if (countdown === 0) {
        clearInterval(timer)
        isDisabled.value = false
        buttonText.value = '获取验证码'
      }
    }, 1000)
  }
}


const rules = ref({
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' },
  ],
  emailCode: [
    { required: true, message: '验证码不能为空', trigger: 'blur' },
    { min: 4, max: 4, message: '请输入正确验证码', trigger: 'blur' }
  ]
})
const formRef = ref()
const onSubmit = async () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      const resp = await checkECodeService(forgotState.getFUser())
      console.log(forgotState.getFUser())
      if (resp.code === 1) {
        successMsg(resp.data)
        await router.push('/user/forgot/change')
      }
    } else {
      console.log('验证失败')
    }
  })
}
</script>

<template>
  <el-form
    :model="forgotState.fUser"
    :rules="rules"
    ref="formRef"
    style="max-width: 320px"
    label-width="auto"
    class="demo-ruleForm"
  >
    <el-form-item label="用户名：" prop="username">
      <el-input disabled style="width: 300px" v-model="forgotState.fUser.username" />
    </el-form-item>
    <el-form-item label="邮箱：" prop="email">
      <el-input placeholder="请输入邮箱地址" style="width: 300px" v-model="forgotState.fUser.email" />
    </el-form-item>
    <el-form-item label="验证码：" prop="emailCode">
      <el-input placeholder="点击按钮发送验证码到邮箱" style="width: 300px" v-model="forgotState.fUser.emailCode" />
      <el-button :disabled="isDisabled" style="margin-top: 10px" @click.prevent="getECode">
        {{ buttonText }}
      </el-button>
    </el-form-item>
    <div style=" text-align: center;margin-bottom: 15px">
      <el-button style="width: 250px" size="large" round type="primary" @click="onSubmit">
        下一步&nbsp;<arrow-circle-right class="icon-center" theme="outline" size="18" :strokeWidth="4" />
      </el-button>
    </div>
  </el-form>
</template>

<style scoped>

</style>
